<template>
  <el-dropdown @command="handleCommand" trigger="click" class="table-headSelect">
    <el-button class="centerBtn">
      <template v-if="selectItem">
        <span>{{ selectItem.label }}</span>
        <template v-if="selectItem.count">
          <font>：</font>
          <span class="item_count">{{ selectItem.count }}</span>
        </template>
      </template>
      <template v-else>
        <span>{{ defaultSelect.label }}</span
        ><font v-if="defaultSelect.count">：</font>
        <span v-if="defaultSelect.count" class="item_count">{{
          defaultSelect.count
        }}</span>
      </template>
      <i class="el-icon-arrow-down el-icon--right"></i>
    </el-button>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item v-for="(item, index) in selectList" :key="index" :command="item">
        <span>{{ item.label }}</span
        ><font v-if="item.count >= 0">：</font>
        <span class="item_count">{{ item.count }}</span>
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
export default {
  name: "tableHeadSelect",
  data() {
    return {
      selectItem: null,
    };
  },
  computed: {
    defaultSelect() {
      let defaultItem = this.selectList.find((v) => {
        return v.default === true;
      });
      if (defaultItem) return defaultItem;
      else {
        return {
          label: "全部",
          count: 0,
        };
      }
    },
  },
  props: {
    selectList: {
      type: Array,
      required: true,
    },
  },
  watch: {
    selectList: {
      handler(value){
        if(this.selectItem && this.selectItem.label && Array.isArray(value)){
          for(let i = 0; i < value.length; i++){
            const ele = value[i]
            if(ele.label == this.selectItem.label){
              this.selectItem = ele
              break;
            }
          }
        }
      },
      deep: true
    }
  },

  methods: {
    handleCommand(command) {
      this.selectItem = command;
      this.$emit("headSelectChange", command);
    },
    clear(){
      this.selectItem = null
    }
  },
};
</script>

<style lang="less" scoped>
.table-headSelect {
  vertical-align: top;
  .centerBtn {
    height: 33px;

    padding: 8px 24px;
  }
  .item_count {
    margin-left: 8px;
  }
}
</style>
